package com.hwtx.form.assistant;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.cloud.ai.dashscope.api.DashScopeResponseFormat;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import io.geekidea.boot.config.properties.BootProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

@Slf4j
@Service
public class CustomerSupportAssistant {

    private final ChatClient chatClient;

    public CustomerSupportAssistant(MessageChatMemoryAdvisor messageChatMemoryAdvisor, @Qualifier("dashscopeChatModel") ChatModel chatModel) {
        BootProperties bootProperties = SpringUtil.getBean(BootProperties.class);
        BootProperties.AssistConfig assistantConfig = bootProperties.getAssistant();

        this.chatClient = ChatClient.builder(chatModel)
                .defaultSystem(assistantConfig != null ? assistantConfig.getSystemText() : "").defaultAdvisors(
                        new SimpleLoggerAdvisor(),
                        messageChatMemoryAdvisor)
                .build();
    }

    public Flux<String> chat(String chatId, String prompt) {

        var runtimeOptions = DashScopeChatOptions.builder()
                .withTemperature(0.8)
                .withResponseFormat(DashScopeResponseFormat.builder()
                        .type(DashScopeResponseFormat.Type.JSON_OBJECT)
                        .build()).build();

        ChatClient.ChatClientRequestSpec clientRequestSpec = chatClient.prompt()
                .options(runtimeOptions)
                .user(prompt)
                .advisors(memoryAdvisor -> memoryAdvisor.param(ChatMemory.CONVERSATION_ID, chatId));
        return clientRequestSpec.stream().content();
    }
}